package fun.cyhgraph.aop;

import fun.cyhgraph.annotation.AuthCheck;
import fun.cyhgraph.common.ErrorCode;
import fun.cyhgraph.common.UserConstant;
import fun.cyhgraph.common.UserRoleEnum;
import fun.cyhgraph.model.entity.User;
import fun.cyhgraph.exception.BusinessException;
import fun.cyhgraph.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;




@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        // 当前登录用户
        User loginUser = userService.getLoginUser(request);

        // 获取用户角色
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getRole());
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        // 解析角色组合
        if (UserConstant.ADMIN_OR_MERCHANT_ROLE.equals(mustRole)) {
            // 允许 ADMIN 或 MERCHANT 角色访问
            if (!UserRoleEnum.ADMIN.equals(userRoleEnum) && !UserRoleEnum.MERCHANT.equals(userRoleEnum)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 其他角色校验
            UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
            if (mustRoleEnum == null || !mustRoleEnum.equals(userRoleEnum)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }

        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}